#pragma once

#include "Message.h"
#include "ThreadSafer.h"
#include <list>



namespace _FOGGE_
{
	namespace _MSG_
	{

		template <class T>
		class MessageQueue
			: public _FOGGE_::_THREAD_::ThreadSafer  
		{

			BOOST_MPL_ASSERT((boost::is_convertible<T*,Message*>));


			std::list<T*>	m_Messages;
		public:
			MessageQueue()
			{

			}
			~MessageQueue()
			{
				Clear();
			}

			void        Clear(type_moduleid finishedid=eEMID_ModuleCount)
			{
				
				_FOGGE_::_THREAD_::Lock locker(&m_cs);
				int size=m_Messages.size();

				std::list<T*>::iterator iterMessage, end;

				end=m_Messages.end();

				for( iterMessage = m_Messages.begin(); iterMessage != end; ++iterMessage )
				{
					if(finishedid==eEMID_ModuleCount)
						(*iterMessage)->FreeToPoolIfNotUsing();
					else
						(*iterMessage)->FreeToPoolIfNotUsing(finishedid);
					
				}

				m_Messages.clear();

			}
			void        AddMessage( T* ptrMessage)
			{
				_FOGGE_::_THREAD_::Lock locker(&m_cs);
				m_Messages.push_back( ptrMessage );
			}
			T*			GetMessage( )
			{

				if( m_Messages.empty() == true )
					return NULL;

				T* pMessage;

				_FOGGE_::_THREAD_::Lock locker(&m_cs);

				pMessage = *m_Messages.begin();
				m_Messages.pop_front();

				return pMessage;
			}

		};
	}
}